<template>
  <div>
    <zm-panel
      :title="`${TITLE}特殊节假日规则`"
      :visible.sync="value"
      @change="close"
    >
      <div class="pd20">
        <zm-form :model="form" ref="form" :rules="rules">
          <zm-form-item label="产品类型" prop="type">
            <el-radio-group v-model="form.type" @change="handleChangetype">
              <el-radio label="1">兑换券</el-radio>
              <el-radio label="2">优惠券</el-radio>
            </el-radio-group>
          </zm-form-item>
          <zm-form-item label="特殊节假日方案名称" prop="name">
            <zm-input
              v-model="form.name"
              class="w300"
              maxlength="30"
              show-word-limit
            ></zm-input>
          </zm-form-item>
          <zm-form-item label="券兑换范围" prop="exchangeRange">
            <el-radio-group
              v-model="form.exchangeRange"
              @change="handleResetRuleItem"
            >
              <el-radio label="1" :disabled="isDisOnline">线上</el-radio>
              <el-radio label="2" v-if="form.type === '1'" :disabled="isDisOffline">线下</el-radio>
            </el-radio-group>
          </zm-form-item>
          <!-- 线上规则 -->
          <online-special
            v-if="form.exchangeRange === '1'"
            :rule="form.rule"
            @change="handleSetRule"
            ref="specialRule"
            :is-disabled-limit-rule="isDisabledLimitRule"
          />
          <!-- 线下规则 -->
          <offline-special
            v-if="form.exchangeRange === '2'"
            :rule="form.rule"
            @change="handleSetRule"
            ref="specialRule"
          />
        </zm-form>
      </div>
      <div slot="footer" class="tc">
        <zm-button @click="close" type="info">取消</zm-button>
        <zm-button
          @click="onSave"
          type="primary"
          v-if="isPlanConfig || isApproval"
        >
          {{ id ? "确认修改" : "保存" }}
        </zm-button>
        <zm-button @click="onSave('submit')" type="primary" v-else>
          提交审批
        </zm-button>
      </div>
    </zm-panel>
  </div>
</template>
<script>
import panelMixin from '@/mixins/panelMixin'
import ZmCollapseForm from '@/components/ZmCollapseForm'
import OnlineSpecial from './components/OnlineSpecial'
import OfflineSpecial from './components/OfflineSpecial'
import productProgramApis from '@/api/src/productProgram'
import approveApis from '@/api/src/approve'
import { DEFAULT_ITEM } from './const'
import { PROCESS_TYPE } from '@/model'

export default {
  name: 'SetSpecialRule',
  components: { OnlineSpecial, OfflineSpecial },
  mixins: [panelMixin],
  props: {
    id: {
      type: [String, Number],
      default: ''
    },
    params: {
      type: Object,
      default () {
        return {}
      }
    },
    // 入口是否是从方案配置进来
    isPlanConfig: {
      type: Boolean,
      default: false
    },
    // 入口是否是从已售销售单进来
    isSaleOrder: {
      type: Boolean,
      default: false
    },
    isApproval: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      DEFAULT_ITEM,
      form: {
        type: '1',
        name: '',
        exchangeRange: '',
        rule: []
      },
      isDisabledLimitRule: false // 是否禁用线上规则的指定时间段补差
    }
  },
  computed: {
    isDisOnline () {
      if (this.id) {
        return this.id && this.form.exchangeRange === '2'
      } else {
        return false
      }
    },
    isDisOffline () {
      if (this.id) {
        return this.id && this.form.exchangeRange === '1'
      } else {
        return false
      }
    },
    TITLE () {
      return this.id ? '编辑' : '添加'
    },
    rules () {
      const ruleList = Object.keys(this.form)
      let rulesObj = {}
      ruleList.forEach((item) => {
        rulesObj[item] = {
          required: true,
          message: '*为必填项，不能为空',
          trigger: 'blur'
        }
      })
      return rulesObj
    },
    // 审批类型 8->销售单特殊价格配置；2->产品特殊价格配置
    processType () {
      return this.isSaleOrder
        ? PROCESS_TYPE.saleOrderSpecialConfig
        : PROCESS_TYPE.specPrice
    },
    isDraft () {
      return ['2', '4', '1'].includes(this.form.checkStatus)
    }
  },
  watch: {},
  created () {
    if (this.id) {
      this.init()
    }
  },
  methods: {
    async init () {
      const draftID = this.params.draftId || ''
      const _res = await productProgramApis.getInfo({
        id: this.id,
        draftId: draftID
      })
      this.isDisabledLimitRule = _res.type === '2'
      this.form = _res
    },
    // 线上线下回调赋值
    handleSetRule (val) {
      this.$set(this.form, 'rule', val)
    },
    // 切换兑换券数据处理
    handleChangetype (val) {
      if (val === '2') {
        this.$set(this.form, 'exchangeRange', '1')
        this.isDisabledLimitRule = true
      } else {
        this.isDisabledLimitRule = false
      }
    },
    onSave (type) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.$refs.specialRule
            .validate().then(async () => {
              const res = this.id
                ? await productProgramApis.update({
                  id: this.id,
                  ...this.form,
                  ...this.params
                })
                : await productProgramApis.create({
                  ...this.form,
                  ...this.params
                })
              if (type === 'submit') {
                approveApis
                  .checkApprove({ processType: this.processType }).then(() => {
                    this.onSubmit(this.id, res.draftId)
                  }).catch(err => err)
              } else {
                this.$message.success('操作成功')
                this.$emit('re-load')
                this.close()
              }
            })
            .catch((err) => {
              this.$message.warning(`${err}有未填项，请完善`)
            })
        }
      })
    },
    onSubmit (businessId, draftId) {
      this.$confirm(
        '确认提交？审批通过后所有关联此方案的销售单特殊节假日方案将更新，请谨慎操作!',
        '确认提交？',
        { type: 'warning' }
      )
        .then(async () => {
          await approveApis.submit({
            processType: this.processType,
            linkName: this.form.name,
            businessId: businessId,
            draftId: draftId
          })
          this.$message.success('操作成功')
          this.$emit('re-load')
          this.close()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 线上线下模板切换初始化
    handleResetRuleItem (val) {
      const DEFAULT_ITEM = JSON.parse(JSON.stringify(this.DEFAULT_ITEM))
      console.log(DEFAULT_ITEM, 'DEFAULT_ITEM')
      this.$set(this.form, 'rule', [DEFAULT_ITEM])
    }
  }
}
</script>
<style scoped lang="scss"></style>
